<template>
  <div class="update-photo">
    <img class="img" :src="imgsrc" ref="imgphoto" />

    <div class="toolbar">
      <div class="cancel" @click="$emit('cancel')">取消</div>
      <div class="confirm" @click="confirm">完成</div>
    </div>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";

import  {Toast} from 'vant'

import { updateUserPhotoApi } from "@/api";
export default {
  name: "",
  data() {
    return {
      cropper: null
    };
  },
  props: ["imgsrc"],
  methods: {
    confirm() {
      // 获取裁切后的图片资源 + 发送请求传递参数

      this.cropper.getCroppedCanvas().toBlob(
        blob => {
          this.photoCropper(blob);
        } /*, 'image/png' */
      );
    },
    async photoCropper(blob) {
      Toast.loading({
        message: "加载中...",
        forbidClick: true
      });
      const formData = new FormData();

      // Pass the image file name as the third parameter if necessary.
      formData.append("photo", blob /*, 'example.png' */);

      // Use `jQuery.ajax` method for example
      //   $.ajax("/path/to/upload", {
      //     method: "POST",
      //     data: formData,
      //     processData: false,
      //     contentType: false,
      //     success() {
      //       console.log("Upload success");
      //     },
      //     error() {
      //       console.log("Upload error");
      //     }
      //   });

      const { data: res } = await updateUserPhotoApi(formData);
      console.log(res, 777755555);
      this.$emit("success");
    }
  },
  mounted() {
    const image = this.$refs.imgphoto;
    this.cropper = new Cropper(image, {
      //aspectRatio: 16 / 9,
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      // autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false
    });
  }
};
</script>

<style scoped lang="less">
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
